package com.skin;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.skin.SkinInfo.Author;
import com.skin.SkinInfo.Version;

import android.content.res.Resources;
import android.graphics.drawable.Drawable;

public class SkinInfoHandler extends DefaultHandler {
	private static final String REGEX_REFERENCE = "@(.*)\\\\(.*)";

	private static final String XML_NODE_SKININFO = "SkinInfo";
	private static final String XML_NODE_VERSION = "Version";
	private static final String XML_NODE_AUTHORS = "Authors";
	private static final String XML_NODE_AUTHOR = "Author";

	private static final String XML_ATTR_UUID = "uuid";
	private static final String XML_ATTR_ICON = "icon";
	private static final String XML_ATTR_NAME = "name";
	private static final String XML_ATTR_CODE = "code";
	private static final String XML_ATTR_MIN = "min";
	private static final String XML_ATTR_MAX = "max";
	private static final String XML_ATTR_COMPANY = "company";
	private static final String XML_ATTR_HOME = "home";
	private static final String XML_ATTR_EMAIL = "email";

	private Resources res;

	private UUID uuid;
	private String name;
	private Drawable icon;
	private Version version;
	private Author[] authors;

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if (XML_NODE_SKININFO.equals(localName)) {
			uuid = UUID.fromString(attributes.getValue(XML_ATTR_UUID));
			name = (String) parseResource(attributes.getValue(XML_ATTR_NAME));
			icon = (Drawable) parseResource(attributes.getValue(XML_ATTR_ICON));
		} else if (XML_NODE_VERSION.equals(localName)) {

		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
	}

	private Object parseResource(String refstr) {
		int id = 0;
		Object obj = null;
		Pattern pattern = Pattern.compile(REGEX_REFERENCE);
		Matcher matcher = pattern.matcher(refstr);
		if (matcher.matches()) {
			String type = matcher.group(1);
			String name = matcher.group(2);
			id = res.getIdentifier(name, type, XML_ATTR_CODE);
			if ("string".equals(type)) {
				obj = res.getString(id);
			} else if ("drawable".equals(type)) {
				obj = res.getDrawable(id);
			}
		} else {
			obj = refstr;
		}
		return obj;
	}
}
